package com.imooc.controller;

import com.imooc.VO.ProductInfoVO;
import com.imooc.VO.ProductVO;
import com.imooc.VO.ResultVO;
import com.imooc.domain.ProductCategory;
import com.imooc.domain.ProductInfo;
import com.imooc.service.ProductCategoryService;
import com.imooc.service.ProductInfoService;
import com.imooc.utils.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 买家商品
 * Create By Liuqz
 *
 * @date 2018/5/31 0:48
 */
@RestController
@RequestMapping(value = "/buyer/product")
public class BuyerProductController {

	@Autowired
	private ProductInfoService productInfoService;

	@Autowired
	private ProductCategoryService productCategoryService;

    @GetMapping(value = "/list")
	@Cacheable(cacheNames = "product", key = "123")
    public ResultVO list(){

    	//1.查询所有的上架商品
		List<ProductInfo> productInfoList = productInfoService.findUpAll();

		//2.查询所有商品的类目(一次性查询)
		//使用Java 8 lamba
		List<Integer> types = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());

		List<ProductCategory> productCategoryList = productCategoryService.findByCategoryTypeIn(types);

		//3.数据拼装
		List<ProductVO> productVOList = new ArrayList<>();
		for (ProductCategory productCategory : productCategoryList){
			ProductVO productVO = new ProductVO();
			productVO.setCategoryName(productCategory.getCategoryName());
			productVO.setCategoryType(productCategory.getCategoryType());

			List<ProductInfoVO> productInfoVOList = new ArrayList<>();
			for (ProductInfo productInfo : productInfoList){
				if (productCategory.getCategoryType().equals(productInfo.getCategoryType())) {
					ProductInfoVO productInfoVO = new ProductInfoVO();
					BeanUtils.copyProperties(productInfo, productInfoVO); //将productInfo的属性copy到productInfoVO
					productInfoVOList.add(productInfoVO);
				}
			}
			productVO.setProductVOS(productInfoVOList);
			productVOList.add(productVO);
		}

		return ResultVOUtil.success(productVOList);

    }
}
